import { defineStore } from 'pinia'

export const useVacationStore = defineStore('vacation', {
  state: () => ({
    holidayData: {},
    otherHolidays: {},
    isLoading: false,
    error: null,
    currentYear: new Date().getFullYear()
  }),

  actions: {
    async fetchHolidayData(year) {
      this.isLoading = true
      this.error = null
      this.currentYear = year
      try {
        const response = await fetch(`https://timor.tech/api/holiday/year/${year}`)
        const data = await response.json()

        if (data.code === 0) {
          const formattedData = {}
          Object.entries(data.holiday).forEach(([shortDate, info]) => {
            const fullDate = `${year}-${shortDate}`
            formattedData[fullDate] = info
          })
          this.holidayData = formattedData

          this.otherHolidays = this.generateOtherHolidays(year)
        } else {
          throw new Error(data.message || '获取数据失败')
        }
      } catch (err) {
        this.error = err.message || '获取数据失败'
      } finally {
        this.isLoading = false
      }
    },

    generateOtherHolidays(year) {
      return {
        [`${year}-02-14`]: { name: '情人节', type: 'festival' },
        [`${year}-03-08`]: { name: '妇女节', type: 'festival' },
        [`${year}-03-12`]: { name: '植树节', type: 'festival' },
        [`${year}-05-04`]: { name: '青年节', type: 'festival' },
        [`${year}-06-01`]: { name: '儿童节', type: 'festival' },
        [`${year}-08-01`]: { name: '建军节', type: 'festival' },
        [`${year}-09-10`]: { name: '教师节', type: 'festival' },
        [`${year}-12-24`]: { name: '平安夜', type: 'festival' },
        [`${year}-12-25`]: { name: '圣诞节', type: 'festival' }
      }
    }
  },

  persist: true
})
